﻿var DBDefer; //数据库缓存
var DBVersion = null; //数据库版本
var DBHandle = null; //处理
//初始化数据库
function InitializeDatabase() {
    DBDefer = $.Deferred();
    //获取数据库信息
    var dbBase = GetDataBase();
    //检查数据库是否存在 
    dbBase.transaction(CheckDataVersionTableExistsQuery, DetermineDataVersionError, successCB);
    //创建了一个promise对象，具有state、always、then、primise方法

    return DBDefer.promise();
}

function CreateDatabase() {
    var defer = $.Deferred();
    var db = GetDatabase();
    db.transaction(function (tx) {
        tx.executeSql(DropDataVersionSql);
        tx.executeSql(CreateDataVersionSql);

        // insert current version
        tx.executeSql(InsertSysVersionEntrySql, [VersionId, "1.0"]);

        // create company tables
        tx.executeSql(CreateDataTableCompanySql);
        tx.executeSql(CreateDataTableCompanyAddressSql);
        tx.executeSql(CreateDataTableCompanyContactNumberSql);
        tx.executeSql(CreateDataTableCompanyEmailSql);

        // create contact table
        tx.executeSql(CreateDataTableContactSql);

        // create helpdesk case table
        tx.executeSql(CreateDataTableHelpdeskCaseSql);

        // create user account table
        tx.executeSql(CreateDataTableUserAccountSql);

        // create helpdesk resolution table
        tx.executeSql(CreateDataTableHelpdeskCaseResolutionSql);

        //alert('Running in Test Mode. Data will be reinitialized.');
        DBDefer.resolve();
        defer.resolve(true);

    }, DetermineDataVersionError);
    return defer.promise();
}
// 事务执行成功后调用的回调函数
function successCB() {
    console.log("成功！");
    alert("OK");
}
//
var CheckDataVersionTableExistsSql = "SELECT count(*) AS cnt FROM sqlite_master WHERE type='table' AND name='SysVersion';";
//检查数据库是否存在
function CheckDataVersionTableExistsQuery(tx, results) {
    tx.executeSql(CheckDataVersionTableExistsSql, [], CheckDataVersionTableExistsSuccess, DetermineDataVersionError);
}
//检查数据库版本
function CheckDataVersionTableExistsSuccess(tx, results) {
    if (results.rows.length <= 0) {
        DBVersion = null;
        DBDefer.reject();
        return;
    }

    var tablecount = results.rows.item(0).cnt;
    if (tablecount > 0) {
        // table exists
        CheckDataVersionQuery();
    }
    else {
        // table don't exist
        CreateDatabase();
        CheckDataVersionQuery();
    }
}

function GetDataBase() {
    if (DBHandle != null)
        return DBHandle;
    DBHandle = window.openDatabase("SugarDB", "1.0", "SugarDB", 5000000);
    return DBHandle;
}
//事务执行出错后调用的回调函数
function DetermineDataVersionError(tx, err) {
    alert(tx.message);
    DBVersion = null;
    DBDefer.reject();
}